package com.taotao.rest.service.ipml;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.utils.JsonUtils;
import com.taotao.mapper.TbItemMapper;
import com.taotao.pojo.TbItem;
import com.taotao.rest.dao.IJedisClient;
import com.taotao.rest.service.IItemService;

/**
 * 商品信息
 * 
 * @author Administrator
 *
 */
@Service
public class ItemServiceIpml implements IItemService {
	@Autowired
	private TbItemMapper itemMapper;
	@Autowired
	private IJedisClient jedisClient;

	@Value("${REDIS_ITEM_KEY}")
	private String REDIS_ITEM_KEY;// 商品信息

	@Value("${REDIS_ITEM_EXPIRE}")
	private Integer REDIS_ITEM_EXPIRE;// 缓存的过期时间

	/**
	 * 通过id获取商品信息
	 */
	@Override
	public TaotaoResult getItemInfoById(Long itemId) {
		// TODO Auto-generated method stub
		// 从redis缓存中获取数据
		try {
			String hget = jedisClient.get(REDIS_ITEM_KEY + ":" + itemId
					+ ":base");
			if (StringUtils.isNotBlank(hget)) {
				TbItem item = JsonUtils.jsonToPojo(hget, TbItem.class);
				return TaotaoResult.ok(item);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		// 通过id查询商品信息
		TbItem item = this.itemMapper.selectByPrimaryKey(itemId);
		// 将商品信息添加到redis缓存
		try {
			String jsonStr = JsonUtils.objectToJson(item);
			this.jedisClient.set(REDIS_ITEM_KEY + ":" + itemId + ":base",
					jsonStr);
			// 设置过期时间
			this.jedisClient.expire(REDIS_ITEM_KEY + ":" + itemId + ":base",
					REDIS_ITEM_EXPIRE);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return TaotaoResult.ok(item);
	}
}
